package com.hp.appfw.task;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.jms.Message;
import javax.jms.ObjectMessage;

import org.apache.log4j.Logger;
import org.springframework.jms.core.JmsTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hp.appfw.data.mode.mygen.BaseMessageMission;
import com.hp.appfw.data.mode.mygen.MsUserTerminal;
import com.hp.appfw.service.cust.MsUserTerminalService;
import com.hp.appfw.util.PushUtil;
import com.hp.appfw.util.SpringUtil;




public class TaskPush {

	private static Logger logger = Logger.getLogger(TaskPush.class);
	private static String taskName = "MessagePushTask";
	private static String taskId = UUID.randomUUID().toString(); 
	private static long procNumber = 0;
	private static long errorNumber = 0;
	private static long missionCount = 0;
	private static Date lastUpdateTime = new Date();
	
	
	
	
	private static final int updateIntervalTime = 300000;
	public static boolean pushMessage(HashMap<String, String> content,String recieverId)
	{
		PushUtil pushUtil = (PushUtil)SpringUtil.getBean("pushUtil");
		MsUserTerminalService terminalService = (MsUserTerminalService)SpringUtil.getBean("msUserTerminalService");
		ObjectMapper mapper = new ObjectMapper();
		String message;
		//TODO
		List<MsUserTerminal> termList = terminalService.selectTerminalByUser(recieverId);
		
		int pushCount = 0;
		//create message by type
		for(MsUserTerminal term : termList)
		{
			switch(term.getPlatformType())
			{
				case "iPhone":
				case "iPad":
				{
					Map<String, Object> addInfo = new HashMap<String, Object>();
					addInfo.put("alert", content.get("title"));
					addInfo.put("sound", "default");
					//addInfo.put("badge", 0);
	
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("title", content.get("title"));
					param.put("description", content.get("summary"));
					
					//param.put("msgId", content.get("msgId"));
					
					param.put("type", content.get("type"));
					//param.put("orgId", content.get("orgId"));
					param.put("courseId", content.get("courseId"));
					//param.put("contentId", content.get("contentId"));
					//param.put("status", content.get("status"));
					param.put("extra", content.get("extra"));

					param.put("aps", addInfo);
	
					try {
						message = mapper.writeValueAsString(param);
						
					
						
						pushUtil.push(content.get("msgId").trim(), PushUtil.DEVICE_IOS, Long.parseLong(term.getChannelId().trim()), term.getDeviceInfo(), message);
						pushCount ++;
						logger.info("[" + taskId + ", " + taskName + "]Message push success.");
					} catch (Exception e) {
						logger.error("[" + taskId + ", " + taskName + "]Message push error:\r\n" + e.toString());
					}
				}
				break;
				case "AndriodPhone":
				case "AndriodPad":
				{
					Map<String, Object> addInfo = new HashMap<String, Object>();
					addInfo.put("title", content.get("title"));
					addInfo.put("description", content.get("summary"));

					//addInfo.put("msgId", content.get("msgId"));
					
					addInfo.put("type", content.get("type"));
					//addInfo.put("orgId", content.get("orgId"));
					addInfo.put("courseId", content.get("courseId"));
					//addInfo.put("contentId", content.get("contentId"));
					//addInfo.put("status", content.get("status"));
					addInfo.put("extra", content.get("extra"));
	
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("title", content.get("title"));
					param.put("description", content.get("summary"));
					param.put("custom_content", addInfo);
	
					try {
						message = mapper.writeValueAsString(param);
						pushUtil.push(content.get("msgId").trim(), PushUtil.DEVICE_ANDROID, Long.parseLong(term.getChannelId().trim()), term.getDeviceInfo().trim(), message);
						pushCount ++;
						logger.info("[" + taskId + ", " + taskName + "]Message push success.");
					} catch (Exception e) {
						logger.error("[" + taskId + ", " + taskName + "]Message push error:\r\n" + e.toString());
					}
				}
				break;
			}
		}
		if(termList.size() == 0)
		{
			logger.info("[" + taskId + ", " + taskName + "]No terminal can be found.");
			return true;
		}
		else
		{
			if(pushCount > 0)
				return true;
			else
				return false;
		}
	}
	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws Exception{
		
		
		JmsTemplate jmsTemplate = (JmsTemplate)SpringUtil.getBean("terminalTemplate");
    	ObjectMapper mapper = new ObjectMapper();
		try{

			logger.info("[" + taskId + ", " + taskName + "] Task had been created and wait for incoming message.");

			
			while(true)
			{
				Message msg = (Message)jmsTemplate.receive();
				if(msg instanceof ObjectMessage)
				{
					if(msg != null)
					{	
						
						BaseMessageMission mission = (BaseMessageMission)((ObjectMessage)msg).getObject();
						HashMap mapContent = (HashMap<String, String>)mapper.readValue(mission.getContent(), HashMap.class);
						mapContent.put("msgId", mission.getId());
						List<String> recieverIds=mission.getRecieverIds();
						for(String recieverId:recieverIds){
							pushMessage(mapContent,recieverId);
						}
					
					}
				}
			}
		}catch(Exception ex)
		{
			logger.error("[" + taskId + ", " + taskName + "] Task had beed terminated by exception. exception info:" + ex.toString());
			ex.printStackTrace();

		}
	}

}
